import type {
  BaseStyleConfig,
  IPersonalizationItemConfig,
} from '../../../../types/interfaces'
import { UploadInput } from '../../../../components/combined/upload_input'
import { UserPref } from '../../../../lib/abstract'
import { PageManager } from '../../../../lib/abstract/page_manager'
import { ToolKit } from '../../../../lib/utils/toolkit'
import {
  AppStyleCollections,
  logger,
  VALID_RESULT,
} from '../../../../types/constants'
import { FILE_UPLOAD_MODE } from '../../../../types/interfaces'
import { BackgroundImageService } from './service'

export class BackgroundImage extends UserPref {
  // @Decorators.Identity
  readonly id = 'background_image'
  readonly name = 'BackgroundImage'
  // @Decorators.Dependency
  private readonly service: BackgroundImageService = new BackgroundImageService()
  private readonly pageManager: PageManager = PageManager.getInstance()
  // @Decorators.InheritedCoreConfig
  useDomainIsolation: boolean = false
  // @Decorators.InheritedConfig
  readonly styleConfigKey = 'backgroundImage'
  readonly cssProperty = ''
  readonly cssValueSuffix = ''
  readonly defaultMode: FileUploadMode = FILE_UPLOAD_MODE.URL
  // @Decorators.UIElement
  private readonly urlUploadDesc = '已上传文件'

  constructor(config: IPersonalizationItemConfig) {
    super(config)
    this.modeIsUsed = true
  }

  createComponent(config: BaseStyleConfig, value: string, mode: string, debouncedSave: (() => void) & { flush: () => void }): UploadInput {
    const id = this.generateId(config.styleVar)

    return new UploadInput({
      id: this.id,
      label: '背景图片',
      urlValue: value,
      mode,
      onUrlChange: (url: string, _componentId: string) => {
        if (this.urlUploadDesc === url)
          return
        this.cachedValues.set(id, url)
        this.lastModes.set(id, this.cachedModes.get(id) as string)
        this.cachedModes.set(id, FILE_UPLOAD_MODE.URL)
        debouncedSave()
      },
      onFileChange: async (files, _componentId: string) => {
        if (files && files.length > 0) {
          try {
            // 处理文件上传逻辑
            const file = files[0]
            // 等待文件处理完成
            this.cachedValues.set(id, await ToolKit.browser.file.readFileAsDataURL(file)) // 直接读取文件
            this.lastModes.set(id, this.cachedModes.get(id) as string)
            this.cachedModes.set(id, FILE_UPLOAD_MODE.FILE)
            this.saveChanges(id)
          }
          catch (error: any) {
            logger.error(`[${this.name}] 文件上传失败:`, error)
          }
        }
      },
      placeholder: '输入图片URL或上传本地图片',
    })
  }

  /**
   * 检查输入值是否有效
   * @param value 输入值
   * @param mode 模式
   * @returns 检查结果
   */
  handleCheck(value: string, mode: string): { status: ValidResultType, error: string } {
    let checkResult: { status: ValidResultType, error: string }

    // 图片支持为空来表示不使用背景图片
    if (!value || value.length === 0) {
      checkResult = { status: VALID_RESULT.VALID.value, error: '' }
    }
    else {
      checkResult = ToolKit.browser.url.isValidUrl(value, mode as any)
    }

    return checkResult
  }

  applyStyles(): void {
    this.getInstanceIds().forEach((id) => {
      const { value } = this.getStorageValues(id)
      this.service.apply(value)
    })

    // 更新 body 壁纸状态类
    document.body.classList.toggle(AppStyleCollections.Wallpaper.EXISTS, this.pageManager.hasActiveWallpaper())
  }

  afterResetStyle(): void {
    this.service.reset()
  }
}
